package com.pms.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pms.constant.MessageConstant;
import com.pms.dto.MailBoxPageQueryDTO;
import com.pms.dto.MailboxSaveDTO;
import com.pms.dto.MailboxUpdateDTO;
import com.pms.entity.Mailbox;
import com.pms.entity.Owner;
import com.pms.exception.NotFoundException;
import com.pms.mapper.MailboxMapper;
import com.pms.mapper.OwnerMapper;
import com.pms.result.PageResult;
import com.pms.service.MailboxService;
import com.pms.vo.MailboxPageQueryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class MailboxServiceImpl implements MailboxService {

    @Autowired
    private MailboxMapper mailboxMapper;
    @Autowired
    private OwnerMapper ownerMapper;

    /**
     * 信箱新增
     * @param mailboxSaveDTO
     */
    public void save(MailboxSaveDTO mailboxSaveDTO) {
        Owner owner=ownerMapper.getByNameAndPhone(mailboxSaveDTO.getOwnerName(), mailboxSaveDTO.getPhone());
        if(owner==null){
            throw new NotFoundException(MessageConstant.OWNER_NOT_EXIST);
        }

        Mailbox mailbox=new Mailbox();
        mailbox.setContent(mailboxSaveDTO.getContent());
        mailbox.setOwnerId(owner.getId());
        mailbox.setStatusId(10);  // 默认未读
        mailbox.setCreateTime(LocalDateTime.now());

        mailboxMapper.save(mailbox);
    }

    /**
     * 信箱分页查询
     * @param mailBoxPageQueryDTO
     * @return
     */
    public PageResult page(MailBoxPageQueryDTO mailBoxPageQueryDTO) {
        PageHelper.startPage(mailBoxPageQueryDTO.getPage(), mailBoxPageQueryDTO.getPageSize());
        Page<MailboxPageQueryVO> page=mailboxMapper.page(mailBoxPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 批量删除
     * @param ids
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            mailboxMapper.delete(id);
        }
    }

    /**
     * 信箱信息修改
     * @param mailboxUpdateDTO
     */
    public void update(MailboxUpdateDTO mailboxUpdateDTO) {
        Mailbox mailbox=mailboxMapper.getById(mailboxUpdateDTO.getId());
        mailbox.setStatusId(mailboxUpdateDTO.getStatusId());
        mailboxMapper.update(mailboxUpdateDTO);
    }
}
